package services;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import models.GoogleAnalytic;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

public class UpdateGoogleAnalytic {
	public UpdateGoogleAnalytic(String ananyticAccount, String domainName) {
		try {
			ObjectifyService.register(GoogleAnalytic.class);
		} catch (Exception e) {
			//e.printStackTrace();
		}
		Objectify ofy = ObjectifyService.begin();
		GoogleAnalytic googleAnalytic = new GoogleAnalytic();
		try {
			googleAnalytic = ofy.get(new Key<GoogleAnalytic>(GoogleAnalytic.class, ananyticAccount));
			//GoogleAnalytic googleAnalytic = ofy.query(GoogleAnalytic.class).filter("ananyticAccount", ananyticAccount).get();
		} catch (Exception e) {
			googleAnalytic = null;
		}
		
		if (googleAnalytic != null) {
			List<String> domains = googleAnalytic.getDomain();
			if (!domains.contains(domainName) && domains.size() < 100) {
				domains.add(domainName);
			}
			googleAnalytic.setDomain(domains);
		} else {
			googleAnalytic = new GoogleAnalytic();
			googleAnalytic.setAnanyticAccount(ananyticAccount);
			googleAnalytic.setDomain(Arrays.asList(domainName));
		}
		googleAnalytic.setDate(new Date());
		
		ofy.put(googleAnalytic);
		System.out.println("Update ananyticAccount success: " + ananyticAccount);
	}
}
